using QFramework.Framework.Util;
using UnityEngine;

namespace QFramework.Framework.Manager
{
    public class AudioManager : MonoSingleton<AudioManager>
    {
        private AudioListener _audioListener;

        private AudioSource _musicSource;

        private void CheckAudioListener()
        {
            if (!_audioListener) _audioListener = gameObject.AddComponent<AudioListener>();
        }

        public void PlayMusic(string musicName, bool loop)
        {
            CheckAudioListener();

            if (!_musicSource) _musicSource = gameObject.AddComponent<AudioSource>();

            var music = Resources.Load<AudioClip>(musicName);
            _musicSource.clip = music;
            _musicSource.loop = loop;
            _musicSource.Play();
        }

        public void StopMusic()
        {
            _musicSource.Stop();
        }

        public void PauseMusic()
        {
            _musicSource.Pause();
        }

        public void ResumeMusic()
        {
            _musicSource.UnPause();
        }

        public void MusicOff()
        {
            _musicSource.Pause();
            _musicSource.mute = true;
        }

        public void MusicOn()
        {
            _musicSource.UnPause();
            _musicSource.mute = false;
        }

        public void PlaySound(string soundName)
        {
            CheckAudioListener();

            var audioSource = gameObject.AddComponent<AudioSource>();
            var sound = Resources.Load<AudioClip>(soundName);

            audioSource.clip = sound;
            audioSource.Play();
        }

        public void SoundOff()
        {
            var audioSources = GetComponents<AudioSource>();

            foreach (var audioSource in audioSources)
                if (audioSource != _musicSource)
                {
                    audioSource.Pause();
                    audioSource.mute = true;
                }
        }

        public void SoundOn()
        {
            var audioSources = GetComponents<AudioSource>();

            foreach (var audioSource in audioSources)
                if (audioSource != _musicSource)
                {
                    audioSource.UnPause();
                    audioSource.mute = false;
                }
        }
    }
}